<template>
  <div>
    <el-card>
      <div class="gva-table-box">
        <div style="margin-bottom: 20px;">
          <el-input
            v-model="searchInfo.keyword"
            placeholder="请输入项目名称"
            style="width: 15%;margin-right: 20px;"
          />
          <el-select
            v-model="searchInfo.put_status_list"
            style="width: 15%;margin-right: 20px;"
            placeholder="请选择项目状态"
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select
            v-model="hugeSelectColumn"
            multiple
            clearable
            filterable
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="3"
            placeholder="请选择列"
            style="width: 500px;margin-right: 20px;"
            @change="selectHugeColumn"
          >
            <el-option
              v-for="item in hugeColumns"
              :key="item.prop"
              :label="item.label"
              :value="item.prop"
            />
          </el-select>
          <el-button
            type="primary"
            @click="search()"
          >
            查询
          </el-button>
          <el-button
            type="primary"
            style="float: right;"
            @click="create()"
          >创建</el-button>
        </div>
      </div>
      <el-divider />

      <el-table
        ref="multipleTable"
        tooltip-effect="dark"
        row-key="ID"
        :data="hugeTableData"
        border
      >
        <el-table-column
          align="left"
          label="项目名称"
          width="250px"
          prop="name"
          fixed="left"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="group(scope.row)"
            >
              {{ scope.row.name }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="项目ID"
          width="150px"
          prop="campaign_id"
          fixed="left"
        />
        <el-table-column
          v-for="(item,index) in temHugeSelectColumn"
          :key="index"
          :width="item.width"
          align="left"
          :label="item.label"
        >
          <template #default="scope">
            <span style="margin-right: 5px;">
              {{ scope.row[item.prop] }}
            </span>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-drawer
      v-model="createDialog"
      size="60%"
      title="创建计划"
      width="800"
    >
      <el-form
        ref="project"
        :model="projectForm"
        label-position="top"
        :validate-on-rule-change="false"
      >
        <el-form-item
          label="计划名称"
          label-width="140px"
          prop="name"
        >
          <el-input
            v-model="projectForm.campaign_name"
            style="width: 50%;"
          />
        </el-form-item>
        <el-form-item
          label="广告类型"
          label-width="140px"
          prop="ad_type"
        >
          <el-radio-group
            v-model="projectForm.ad_type"
          >
            <el-radio-button
              v-for="(item,index) in ad_type_list"
              :key="index"
              :label="item.value"
            >
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="投放方式"
          label-width="140px"
          prop="put_type"
        >
          <el-radio-group
            v-model="projectForm.put_type"
            @change="putTypeChange"
          >
            <el-radio-button
              v-for="(item,index) in put_type_list"
              :key="index"
              :label="item.value"
            >
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="projectForm.ad_type == 0"
          label="竞价策略"
          label-width="140px"
          prop="bid_type"
        >
          <el-radio-group
            v-model="projectForm.bid_type"
          >
            <el-radio-button
              v-for="(item,index) in bid_type_list"
              :key="index"
              :label="item.value"
            >
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="计划日预算"
          label-width="140px"
          prop="plan_day"
        >
          <el-radio-group
            v-model="projectForm.plan_day"
            @change="planDayChange"
          >
            <el-radio-button
              v-for="(item,index) in plan_day_list"
              :key="index"
              :label="item.value"
            >
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="projectForm.plan_day == 1"
          label="日预算"
          label-width="140px"
          prop="day_budget"
        >
          <el-input
            v-model="projectForm.day_budget"
            placeholder="不小于500,仅支持整数"
            style="width: 30%;"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="projectFormCancel()">取消</el-button>
          <el-button
            type="primary"
            @click="projectFormSubmit('create')"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getAccountData,
  getHugeInfo
} from '@/api/qmAccessTokens'
import { useRouter, useRoute } from 'vue-router'

import JSONBIG from 'json-bigint'
const router = useRouter()
const useRoutes = useRoute()

const account_id = useRoutes.query.account_id

const createDialog = ref(false)

const ad_type_list = ref([
  {
    value: 0,
    label: '展示广告'
  },
  {
    value: 1,
    label: '搜索广告'
  }
])

const put_type_list = ref([
  {
    value: 1,
    label: '全自动投放'
  },
  {
    value: 2,
    label: '智能操盘'
  },
  {
    value: 3,
    label: '常规投放'
  }
])

const bid_type_list = ref([
  {
    value: 0,
    label: '成本优先'
  },
  {
    value: 1,
    label: '最大化转化'
  }
])

const plan_day_list = ref([
  {
    value: 0,
    label: '不限'
  },
  {
    value: 1,
    label: '统一预算'
  },
  {
    value: 2,
    label: '分日预算'
  }
])

const projectForm = ref({
  advertiser_id: account_id,
  campaign_name: '',
  type: 19,
  ad_type: undefined,
  put_type: undefined,
  auto_manage: undefined,
  auto_adjust: undefined,
  auto_build: undefined,
  auto_build_name_rule: {
    unit_name_rule: undefined,
    creative_name_rule: undefined
  },
  bid_type: undefined,
  day_budget: undefined,
  day_budget_schedule: undefined,
  plan_day: undefined,
})

const putTypeChange = (val) => {
  if (val == 1) {
    projectForm.value.auto_manage = 1
    projectForm.value.auto_adjust = 1
    projectForm.value.auto_build = 1
    projectForm.value.auto_build_name_rule = {
      unit_name_rule: '系统自动搭建_[日期][序号]',
      creative_name_rule: '系统自动搭建_[日期][序号]'
    }
  } else if (val == 2) {
    projectForm.value.auto_manage = 0
    projectForm.value.auto_adjust = 1
    projectForm.value.auto_build = 1
    projectForm.value.auto_build_name_rule = {
      unit_name_rule: '系统自动搭建_[日期][序号]',
      creative_name_rule: '系统自动搭建_[日期][序号]'
    }
  } else {
    projectForm.value.auto_manage = 0
    projectForm.value.auto_adjust = 0
    projectForm.value.auto_build = 0
    projectForm.value.auto_build_name_rule = undefined
  }
}

const planDayChange = (val) => {
  if (val == 0) {
    projectForm.value.day_budget = undefined
    projectForm.value.day_budget_schedule = undefined
  } else if (val == 1) {
    projectForm.value.day_budget = undefined
  } else {
    projectForm.value.day_budget_schedule = {
      start_time: '00:00',
      end_time: '23:59',
      day_budget: undefined
    }
  }
}

const create = () => {
  createDialog.value = true
}

const projectFormSubmit = (type) => {
  if (type === 'create') {
    if (!projectForm.value.name) {
      ElMessage.error('项目名称不能为空')
      return
    }
    createDialog.value = false
    ElMessage.success('创建成功')
  }
}

const projectFormCancel = () => {
  createDialog.value = false
}

// =========== 表格控制部分 ===========

const hugeSelectColumn = ref([])

const temHugeSelectColumn = ref([])

const selectHugeColumn = () => {
  temHugeSelectColumn.value = []
  // 把选中的列加入到表格列中
  if (hugeSelectColumn.value.length > 0) {
    hugeSelectColumn.value.forEach(item => {
      hugeColumns.value.forEach(column => {
        if (item === column.prop) {
          temHugeSelectColumn.value.push(column)
        }
      })
    })
  } else {
    temHugeSelectColumn.value = hugeColumns.value
  }
}

const options = [
  {
    value: '1',
    label: '投放'
  },
  {
    value: '2',
    label: '暂停'
  },
  {
    value: '3',
    label: '删除'
  }
]

const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

const hugeTableData = ref([])
// 格式化时间 北京时间
const isShowDate = ref(true)

const searchInfo = ref({
  advertiser_id: account_id,
  page: page.value,
  page_size: pageSize.value,
  keyword: '',
  put_status_list: undefined,
  platform_id: 3
})

const handleCurrentChange = (val) => {
  page.value = val
  searchInfo.value.page = val
  getHugeTableData()
}

const temHugeTableData = ref([])

// 查询
const getHugeTableData = function() {
  getHugeInfo({ params: JSON.stringify(searchInfo.value), type: 'project' }).then(res => {
    if (res.code == 0) {
      hugeTableData.value = []
      temHugeTableData.value = []
      const info = JSONBIG.parse(res.data.info)
      total.value = info.PageInfo.total_number
      info.List.forEach(item => {
        const origin = JSONBIG.parse(item.origin)
        const obj = {
          name: origin.campaign_name,
          campaign_id: origin.campaign_id,
          status: status.value[origin.status],
          put_status: put_status.value[origin.put_status],
          day_budget: origin.day_budget,
          time: origin.create_time,
        }

        if (item.extend) {
          const extend = JSON.parse(item.extend)
          basicInfo.value.forEach(basic => {
            // 如果是浮点型就保留两位小数
            let props = extend[basic.prop]
            if (!Number.isInteger(props)) {
              props = props.toFixed(2)
            }

            if (basic.label.indexOf('率') > -1) {
              obj[basic.prop] = props + '%'
            } else {
              obj[basic.prop] = props
            }
          })
        }

        hugeTableData.value.push(obj)
      })
      console.log(hugeTableData.value)
    }
  })
}

const hugeColumns = ref([
  {
    label: '项目状态',
    prop: 'status',
    width: '150px'
  },
  {
    label: '投放状态',
    prop: 'put_status',
    width: '150px'
  },
  {
    label: '创建时间',
    prop: 'time',
    width: '200px'
  },
  {
    label: '当日预算',
    prop: 'day_budget',
    width: '100px'
  },
  {
    label: '消耗',
    prop: 'charge'
  },
  {
    label: '曝光数',
    prop: 'aclick',
    width: '100px'
  },
  {
    label: '行为数',
    prop: 'bclick'
  },
  {
    label: '千次曝光',
    prop: 'impression_1k_cost',
    width: '120px'
  },
  {
    label: '点击单价',
    prop: 'photo_click_cost',
    width: '100px'
  },
  {
    label: '行为单价',
    prop: 'action_cost',
    width: '100px'
  },
  {
    label: '激活数',
    prop: 'activation'
  },
  {
    label: '千次曝光花费',
    prop: 'click_1k_cost',
    width: '120px'
  },
  {
    label: '激活成本',
    prop: 'click_conversion_ratio',
    width: '100px'
  },
  {
    label: '激活单价',
    prop: 'conversion_cost',
    width: '100px'
  },
  {
    label: '3日留存',
    prop: 'event_three_day_stay_by_conversion'
  },
  {
    label: '7日留存',
    prop: 'event_week_stay_by_conversion'
  },
  {
    label: '转化数',
    prop: 'conversion_num'
  },
  {
    label: '三留率',
    prop: 'event_three_day_stay_by_conversion_ratio'
  },
  {
    label: '7留率',
    prop: 'event_week_stay_by_conversion_ratio'
  },
  {
    label: '转化成本',
    prop: 'conversion_num_cost',
    width: '100px'
  },
  {
    label: '转化率',
    prop: 'conversion_ratio'
  },
  {
    label: '广告LTV',
    prop: 'minigame_iaa_purchase_amount_first_day'
  },
  {
    label: '三日LTV',
    prop: 'minigame_iaa_purchase_amount_three_day_by_conversion'
  },
  {
    label: '七日LTV',
    prop: 'minigame_iaa_purchase_amount_week_by_conversion'
  },
  {
    label: 'ROI',
    prop: 'minigame_iaa_purchase_amount_first_day_roi'
  },
  {
    label: '三日ROI',
    prop: 'minigame_iaa_purchase_amount_three_day_by_conversion_roi'
  },
  {
    label: '七日ROI',
    prop: 'minigame_iaa_purchase_amount_week_by_conversion_roi'
  },
  {
    label: '变现LTV',
    prop: 'minigame_iaa_purchase_amount'
  },
  {
    label: '变现ROI',
    prop: 'minigame_iaa_purchase_roi'
  },
])

const setColumn = () => {
  temHugeSelectColumn.value = []
  hugeColumns.value.forEach(item => {
    temHugeSelectColumn.value.push(item)
  })
}

setColumn()

const group = (row) => {
  router.push({
    name: 'qmCiliGroup', query: { campaign_id: row.campaign_id, advertiser_id: account_id }
  })
}

const basicInfo = ref(
  [
    {
      label: '消耗',
      prop: 'charge'
    },
    {
      label: '曝光数',
      prop: 'aclick'
    },
    {
      label: '行为数',
      prop: 'bclick'
    },
    {
      label: '千次曝光',
      prop: 'impression_1k_cost'
    },
    {
      label: '点击单价',
      prop: 'photo_click_cost'
    },
    {
      label: '行为单价',
      prop: 'action_cost'
    },
    {
      label: '激活数',
      prop: 'activation'
    },
    {
      label: '千次素材曝光花费',
      prop: 'click_1k_cost'
    },
    {
      label: '激活成本',
      prop: 'click_conversion_ratio'
    },
    {
      label: '激活单价',
      prop: 'conversion_cost'
    },
    {
      label: '3日留存',
      prop: 'event_three_day_stay_by_conversion'
    },
    {
      label: '7日留存',
      prop: 'event_week_stay_by_conversion'
    },
    {
      label: '转化数',
      prop: 'conversion_num'
    },
    {
      label: '三留率',
      prop: 'event_three_day_stay_by_conversion_ratio'
    },
    {
      label: '7留率',
      prop: 'event_week_stay_by_conversion_ratio'
    },
    {
      label: '转化成本',
      prop: 'conversion_num_cost'
    },
    {
      label: '转化率',
      prop: 'conversion_ratio'
    },
    {
      label: '广告LTV',
      prop: 'minigame_iaa_purchase_amount_first_day'
    },
    {
      label: '三日LTV',
      prop: 'minigame_iaa_purchase_amount_three_day_by_conversion'
    },
    {
      label: '七日LTV',
      prop: 'minigame_iaa_purchase_amount_week_by_conversion'
    },
    {
      label: 'ROI',
      prop: 'minigame_iaa_purchase_amount_first_day_roi'
    },
    {
      label: '三日ROI',
      prop: 'minigame_iaa_purchase_amount_three_day_by_conversion_roi'
    },
    {
      label: '七日ROI',
      prop: 'minigame_iaa_purchase_amount_week_by_conversion_roi'
    },
    {
      label: '变现LTV',
      prop: 'minigame_iaa_purchase_amount'
    },
    {
      label: '变现ROI',
      prop: 'minigame_iaa_purchase_roi'
    },
  ]
)

const status = ref(
  {
    '1': '广告计划已暂停',
    '3': '广告计划超预算',
    '4': '有效',
    '5': '广告计划已删除',
    '6': '账户余额不足',
    '-2': '不限',
  }
)

const put_status = ref({
  '1': '投放中',
  '2': '暂停',
  '3': '删除',
})

const search = () => {
  getHugeTableData()
}

getHugeTableData()

</script>
<style>
.el-col {
  text-align: center;
}
</style>
